/**
 * Copyright (c) 2024,  科泰集团教研团队
 * 版权所有，请勿侵权
 */
package com.ktjiaoyu.news.dao.impl;

import com.ktjiaoyu.news.dao.NewsDao;
import com.ktjiaoyu.news.dao.BaseDao;
import com.ktjiaoyu.news.entity.News;
import com.ktjiaoyu.news.entity.NewsType;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 新闻
 *
 * @author 科泰集团教研团队
 * @version 1.0.0
 * @createTime 2024-4-17 20:49:54
 * @lastModify 2024-4-17 20:49:54
 */
public class NewsDaoImpl extends BaseDao implements NewsDao {

    @Override
    public List<News> getPage(News entity, Integer pageNo, Integer pageSize) {
        List<News> list = new ArrayList<>();
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            List<Object> params = new ArrayList<>();
            String sql = "select n.*, t.* from news n " +
                    " left join news_type t on(n.typeId = t.id) where 1=1 ";
            sql += createPageCondition(entity, params);
            // sql += " order by xxx , xxx desc"

            sql += " limit ?, ?";
            params.add((pageNo - 1) * pageSize);
            params.add(pageSize);
            stmt = conn.prepareStatement(sql);
            for (int i = 0; i < params.size(); i++) {
                stmt.setObject(i + 1, params.get(i));
            }
            rs = stmt.executeQuery();
            while (rs.next()) {
                News news = new News();
                news.setId(rs.getLong("id"));
                news.setTypeId(rs.getLong("typeId"));
                news.setTitle(rs.getString("title"));
                news.setContent(rs.getString("content"));
                news.setCover(rs.getString("cover"));
                news.setReadCount(rs.getInt("readCount"));
                news.setAuthor(rs.getString("author"));
                news.setPubTime(rs.getDate("pubTime"));
                news.setAdminId(rs.getLong("adminId"));

                NewsType type = new NewsType();
                type.setId(rs.getLong("typeId"));
                type.setTypeName(rs.getString("typeName"));
                type.setRemark(rs.getString("remark"));
                news.setNewsType(type);

                list.add(news);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll(conn, stmt, rs);
        }
        return list;
    }

    @Override
    public int count(News entity) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            List<Object> params = new ArrayList<>();
            String sql = "select count(1) from news where 1=1 ";
            sql += createPageCondition(entity, params);
            stmt = conn.prepareStatement(sql);
            for (int i = 0; i < params.size(); i++) {
                stmt.setObject(i + 1, params.get(i));
            }
            rs = stmt.executeQuery();
            while (rs.next()) {
                return rs.getInt(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll(conn, stmt, rs);
        }
        return 0;
    }

    @Override
    public List<News> getAll() {
        List<News> list = new ArrayList<>();
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            List<Object> params = new ArrayList<>();
            String sql = "select n.*, t.* from news n " +
                    " left join news_type t on(n.typeId = t.id) ";
            stmt = conn.prepareStatement(sql);
            rs = stmt.executeQuery();
            while (rs.next()) {
                News news = new News();
                news.setId(rs.getLong("id"));
                news.setTypeId(rs.getLong("typeId"));
                news.setTitle(rs.getString("title"));
                news.setContent(rs.getString("content"));
                news.setCover(rs.getString("cover"));
                news.setReadCount(rs.getInt("readCount"));
                news.setAuthor(rs.getString("author"));
                news.setPubTime(rs.getDate("pubTime"));
                news.setAdminId(rs.getLong("adminId"));

                NewsType type = new NewsType();
                type.setId(rs.getLong("typeId"));
                type.setTypeName(rs.getString("typeName"));
                type.setRemark(rs.getString("remark"));
                news.setNewsType(type);

                list.add(news);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll(conn, stmt, rs);
        }
        return list;
    }

    @Override
    public News getById(Long id) {
        News news = null;
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            // 获取连接
            conn = getConnection();
            List<Object> params = new ArrayList<>();
            String sql = "select n.*, t.* from news n " +
                    " left join news_type t on(n.typeId = t.id) " +
                    " where n.id=? ";
            // 获取执行sql对象，设置参数
            stmt = conn.prepareStatement(sql);
            stmt.setObject(1, id);
            // 执行获得结果
            rs = stmt.executeQuery();
            while (rs.next()) {
                news = new News();
                news.setId(rs.getLong("id"));
                news.setTypeId(rs.getLong("typeId"));
                news.setTitle(rs.getString("title"));
                news.setContent(rs.getString("content"));
                news.setCover(rs.getString("cover"));
                news.setReadCount(rs.getInt("readCount"));
                news.setAuthor(rs.getString("author"));
                news.setPubTime(rs.getDate("pubTime"));
                news.setAdminId(rs.getLong("adminId"));

                NewsType type = new NewsType();
                type.setId(rs.getLong("typeId"));
                type.setTypeName(rs.getString("typeName"));
                type.setRemark(rs.getString("remark"));
                news.setNewsType(type);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll(conn, stmt, rs);
        }
        return news;
    }

    @Override
    public int insert(News entity) {
        return executeUpdate("INSERT INTO news(`typeId`,`title`,`content`,`readCount`,`author`,`pubTime`,`adminId`) VALUES (?,?,?,?,?,?,?);"
                , entity.getTypeId(), entity.getTitle(), entity.getContent(), entity.getReadCount(), entity.getAuthor(), entity.getPubTime(), entity.getAdminId());
    }

    @Override
    public int[] insertBatch(News... entities) {
        int[] rows = null;
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            conn.setAutoCommit(false);
            String sql = "INSERT INTO news(`typeId`,`title`,`content`,`readCount`,`author`,`pubTime`,`adminId`) VALUES (?,?,?,?,?,?,?);";
            stmt = conn.prepareStatement(sql);
            for (int i = 0; i < entities.length; i++) {
                News entity = entities[i];
                if (entity == null) {
                    continue;
                }
                int j = 1;
                stmt.setObject(j++, entity.getTypeId());
                stmt.setObject(j++, entity.getTitle());
                stmt.setObject(j++, entity.getContent());
                stmt.setObject(j++, entity.getReadCount());
                stmt.setObject(j++, entity.getAuthor());
                stmt.setObject(j++, entity.getPubTime());
                stmt.setObject(j++, entity.getAdminId());
                stmt.addBatch();
            }
            rows = stmt.executeBatch();
            stmt.clearBatch();
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        } finally {
            closeAll(conn, stmt, rs);
        }
        return rows;
    }

    @Override
    public int update(News entity) {
        if (entity == null || entity.getId() == null) {
            return 0;
        }
        List<Object> params = new ArrayList<>();
        String sql = "UPDATE `news` SET ";
        if (entity.getTypeId() != null) {
            sql += " typeId = ? ,";
            params.add(entity.getTypeId());
        }
        if (entity.getTitle() != null && !entity.getTitle().trim().isEmpty()) {
            sql += " title = ? ,";
            params.add(entity.getTitle());
        }
        if (entity.getContent() != null && !entity.getContent().trim().isEmpty()) {
            sql += " content = ? ,";
            params.add(entity.getContent());
        }
        if (entity.getReadCount() != null) {
            sql += " readCount = ? ,";
            params.add(entity.getReadCount());
        }
        if (entity.getAuthor() != null && !entity.getAuthor().trim().isEmpty()) {
            sql += " author = ? ,";
            params.add(entity.getAuthor());
        }
        if (entity.getPubTime() != null) {
            sql += " pubTime = ? ,";
            params.add(entity.getPubTime());
        }
        if (entity.getAdminId() != null) {
            sql += " adminId = ? ,";
            params.add(entity.getAdminId());
        }
        if (params.size() > 0) {
            // 去除逗号
            sql = sql.substring(0, sql.length() - 1);
            sql += " WHERE id = ? ";
            params.add(entity.getId());
            return executeUpdate(sql, params.toArray());
        }
        return 0;
    }

    @Override
    public int deleteByEntity(News entity) {
        if (entity == null) {
            return 0;
        }
        List<Object> params = new ArrayList<>();
        String sql = "delete from news where 1=1 ";
        if (entity.getId() != null) {
            sql += " and id = ?";
            params.add(entity.getId());
        }
        if (entity.getTypeId() != null) {
            sql += " and typeId = ?";
            params.add(entity.getTypeId());
        }
        if (entity.getTitle() != null) {
            sql += " and title = ?";
            params.add(entity.getTitle());
        }
        if (entity.getContent() != null) {
            sql += " and content = ?";
            params.add(entity.getContent());
        }
        if (entity.getReadCount() != null) {
            sql += " and readCount = ?";
            params.add(entity.getReadCount());
        }
        if (entity.getAuthor() != null) {
            sql += " and author = ?";
            params.add(entity.getAuthor());
        }
        if (entity.getPubTime() != null) {
            sql += " and pubTime = ?";
            params.add(entity.getPubTime());
        }
        if (entity.getAdminId() != null) {
            sql += " and adminId = ?";
            params.add(entity.getAdminId());
        }
        if (params.size() == 0) {
            return 0;
        }
        return executeUpdate(sql, params.toArray());
    }

    @Override
    public int deleteById(Long id) {
        return executeUpdate("delete from news where id=?", id);
    }

    @Override
    public int[] deleteBatch(Long... ids) {
        int[] rows = null;
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            conn.setAutoCommit(false);
            String sql = "delete from news where id=?";
            stmt = conn.prepareStatement(sql);
            for (int i = 0; i < ids.length; i++) {
                Long id = ids[i];
                if (id == null) {
                    continue;
                }
                int j = 1;
                stmt.setObject(j++, id);
                stmt.addBatch();
            }
            rows = stmt.executeBatch();
            stmt.clearBatch();
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        } finally {
            closeAll(conn, stmt, rs);
        }
        return rows;
    }

    private String createPageCondition(News entity, List<Object> params) {
        String sql = "";
        if (entity != null) {
            if (entity.getId() != null) {
                sql += " and id = ?";
                params.add(entity.getId());
            }
            if (entity.getTypeId() != null) {
                sql += " and typeId = ?";
                params.add(entity.getTypeId());
            }
            if (entity.getTitle() != null && !entity.getTitle().trim().isEmpty()) {
                sql += " and title like ?";
                params.add("%" + entity.getTitle() + "%");
            }
            if (entity.getContent() != null && !entity.getContent().trim().isEmpty()) {
                sql += " and content = ?";
                params.add(entity.getContent());
            }
            if (entity.getReadCount() != null) {
                sql += " and readCount = ?";
                params.add(entity.getReadCount());
            }
            if (entity.getAuthor() != null && !entity.getAuthor().trim().isEmpty()) {
                sql += " and author like ?";
                params.add("%" + entity.getAuthor() + "%");
            }
            if (entity.getPubTime() != null) {
                sql += " and pubTime = ?";
                params.add(entity.getPubTime());
            }
            if (entity.getAdminId() != null) {
                sql += " and adminId = ?";
                params.add(entity.getAdminId());
            }
        }
        return sql;
    }
}
